package org.javaymw.springboot.controller;

import org.javaymw.springboot.base.BaseController;
import org.javaymw.springboot.base.constant.Constants;
import org.javaymw.springboot.dto.MemberDto;
import org.javaymw.springboot.param.ForgetParam;
import org.javaymw.springboot.param.UpdatePwdParam;
import org.javaymw.springboot.service.MemberService;
import org.javaymw.springboot.util.CookieUtils;
import org.javaymw.springboot.util.MessageUtils;
import org.javaymw.springboot.util.StringUtils;
import org.javaymw.springboot.vo.MemberVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 描述：
 * <p>
 * Author: 赵新国
 * Date: 2017/11/10 17:44
 */
@Controller
public class LoginController extends BaseController {

    @Autowired
    private MemberService memberService;

    /**
     * 跳转到登录页面
     * @return
     */
    @RequestMapping("/login.html")
    public String login(HttpServletRequest request, Model model) {
        // 从cookie里面获取用户信息
        String value = CookieUtils.getValue(request, Constants.MEMBER_COOKIE);
        if (value != null) {
            String[] split = value.split("-");
            model.addAttribute("name", split[0]);
            model.addAttribute("passWord", split[1]);
        }
        return "login";
    }

    /**
     * 登录
     * @return
     */
    @RequestMapping(value = "/signIn", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> signIn(MemberVo memberVo, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> retMap = null;
        if (StringUtils.isBlank(memberVo.getName().trim())) {
            retMap = MessageUtils.error("请输入用户名");
            return retMap;
        }
        if (StringUtils.isBlank(memberVo.getPassWord().trim())) {
            retMap = MessageUtils.error("请输入密码");
            return retMap;
        }
        if (StringUtils.isBlank(memberVo.getCheckCode().trim())) {
            retMap = MessageUtils.error("请输入验证码");
            return retMap;
        }
        if (!getAttribute(request, getSessionId(request)).equals(memberVo.getCheckCode())){
            retMap = MessageUtils.error("验证码输入错误");
            return retMap;
        }
        MemberDto memberDto = memberService.getMemberByParam(memberVo.getName(), memberVo.getPassWord());
        if (memberDto == null) {
            retMap = MessageUtils.error("用户名或密码错误");
            return retMap;
        }
        sessionProvider.setAttribute(request, Constants.MEMBER_SESSION, memberDto);
        /*request.getSession().setAttribute("memberDto", memberDto);*/
        retMap = MessageUtils.success("登录成功");
        // 是否记住用户名、密码
        if (memberVo.getReadmeCode() != null && memberVo.getReadmeCode().equals("on")) {
            // 记住我
            String value = memberDto.getName() + "-" + memberDto.getPassWord();
            // 存入cookie
            CookieUtils.create(response, Constants.MEMBER_COOKIE, value,false, -1, "localhost");
        }
        return retMap;
    }

    /**
     * 退出登录
     * @param request
     * @return
     */
    @RequestMapping(value = "/logout")
    public String logout(HttpServletRequest request) {
        Map<String, Object> retMap = MessageUtils.success();
        /*request.getSession().removeAttribute("memberDto");*/
        sessionProvider.logout(request);
        return "redirect:/login.html";
    }

    /**
     * 跳转到忘记密码页面
     * @param request
     * @return
     */
    @RequestMapping(value = "/forget.html")
    public String forget(HttpServletRequest request) {
        return "forget";
    }

    /**
     * 校验邮件验证码是否正确，正确跳转到重置密码页面
     * @param forgetParam
     * @param model
     * @return
     */
    @RequestMapping(value = "/resetPwd", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> resetPwd(@ModelAttribute ForgetParam forgetParam, Model model) {
        Map<String, Object> retMap = null;
        try {
            // 根据邮箱地址查询会员信息
            MemberDto memberDto = memberService.getMemberByEmail(forgetParam.getEmail());
            if (memberDto == null) {
                retMap = MessageUtils.error("邮箱地址不存在，请输入注册时候的邮箱地址");
                return retMap;
            }
            // 从本地缓存获取邮件验证码
            Object emailCode = cacheManager.getCache("EmailCodeCache").get("emailCode").get();
            if (emailCode == null) {
                retMap = MessageUtils.error("邮件验证码过期，请重新获取");
                return retMap;
            }
            // 校验邮件验证码是否正确
            if (!emailCode.equals(forgetParam.getEmailCode())) {
                retMap = MessageUtils.error("邮件验证码错误");
                return retMap;
            }
            logger.info("emailCode: {}", emailCode);
            retMap = MessageUtils.success(String.valueOf(memberDto.getId()));
            return retMap;
        } catch (Exception e) {
            retMap = MessageUtils.error();
        }
        return retMap;
    }

    /**
     * 跳转到重置密码页面
     * @param id
     * @return
     */
    @RequestMapping(value = "/resetPwd.html", method = RequestMethod.POST)
    public String resetPwd(@RequestParam("id") String id, Model model) {
        model.addAttribute("id", id);
        return "resetPwd";
    }

    /**
     * 重置密码
     * @param updatePwdParam
     * @return
     */
    @RequestMapping(value = "/updatePwd", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> updatePwd(@ModelAttribute UpdatePwdParam updatePwdParam) {
        Map<String, Object> retMap = null;
        try {
            if (!updatePwdParam.getNewPassWord().equals(updatePwdParam.getrNewPassWord())) {
                retMap = MessageUtils.error("新密码和重复密码不一致");
                return retMap;
            }
            MemberDto memberDto = memberService.getMemberById(updatePwdParam.getId());
            if (memberDto != null) {
                if (!updatePwdParam.getPassWord().equals(memberDto.getPassWord())) {
                    retMap = MessageUtils.error("原始密码不正确");
                    return retMap;
                }
                memberDto.setPassWord(updatePwdParam.getNewPassWord());
                if (memberService.updateMemberById(memberDto) == 1) {
                    retMap = MessageUtils.success("重置密码成功");
                } else {
                    retMap = MessageUtils.error("重置密码失败");
                }
            } else {
                retMap = MessageUtils.error("非法用户操作");
            }
        } catch (Exception e) {
            retMap = MessageUtils.error();
        }
        return retMap;
    }

}
